package com.sheng.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sheng.common.Result;
import com.sheng.common.ResultEnum;
import com.sheng.entity.User;
import com.sheng.exception.MyException;
import com.sheng.po.user.LoginPo;
import com.sheng.util.JwtUtils;
import com.sheng.util.RedisUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * The type Login controller.
 *
 * @Author: 王胜
 * @Date 2022 /11/19 17:22
 */
@RestController
@RequestMapping("/login")
@Api(tags = "登录接口")
@Slf4j
public class LoginController {
    /**
     * Login result.
     *
     * @param loginPo the login po
     * @return the result
     */
    @PostMapping
    @ApiOperation("登录")
    public Result login(@RequestBody LoginPo loginPo) {
        LoginPo loginPo1 = new LoginPo();
        loginPo1.setAccount(loginPo.getAccount());
        loginPo1.setPassword(loginPo.getPassword());
        log.info(loginPo.toString());
        User user = new User();
        QueryWrapper<User> queryWrapper = new QueryWrapper<User>();
        queryWrapper.lambda().eq(User::getAccount, loginPo.getAccount());
        user = user.selectOne(queryWrapper);
        if (loginPo.getPassword().equals(user.getPassword())) { //一个简单的登录逻辑
            //获取当前时间戳
            Long currentTimeMillis = System.currentTimeMillis();
            //生成token
            String sign = JwtUtils.sign(loginPo.getAccount(), currentTimeMillis);
            log.info(sign);
            loginPo1.setToken(sign);
            RedisUtils.set(sign, loginPo.getAccount(), JwtUtils.REFRESH_EXPIRE_TIME);
            return new Result<LoginPo>(ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getMsg(), loginPo1);
        } else {
            log.info("密码不正确");

//            return new Result(ResultEnum.ParamException.getCode(), ResultEnum.ParamException.getMsg(), null);
            throw new MyException(ResultEnum.ParamException);
        }
    }
}
